package com.snail.starter.cloud.configuration;

import com.snail.starter.cloud.mapper.JacksonObjectMapper;
import com.snail.starter.iam.authentication.interceptor.AuthenticationInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.util.List;

/**
 * 增加对Long进行String序列化
 *
 * @author snail framework
 */
@Slf4j
@Configuration
public class WebMvcAutoConfiguration implements WebMvcConfigurer {
    /**
     * 拓展mvc框架的消息转换器
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置具体的对象映射器
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //通过设置索引，让自己的转换器放在最前面，否则默认的jackson转换器会在前面，用不上自己配置的转换器
        converters.add(0, messageConverter);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    WebMvcConfigurer webMvcConfigurer(AuthenticationInterceptor authenticationInterceptor, LocaleChangeInterceptor localeChangeInterceptor) {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                if (null != authenticationInterceptor) {
                    registry.addInterceptor(authenticationInterceptor)
                            .addPathPatterns("/**")
                            .excludePathPatterns("/health", "/api-doc", "/actuator/**", "/favicon.ico", "/doc.html", "/swagger-resources/**", "/webjars/**", "/v3/api-docs", "/error");
                }
                if (null != localeChangeInterceptor) {
                    registry.addInterceptor(localeChangeInterceptor)
                            .addPathPatterns("/**");
                }
            }
        };
    }
}
